<template>
  <div class="app-container">
    <div class="filter-container">
      <slot name="filter-content" />
      <el-row>
        <el-col>
          <el-button v-if="options.addRoute" type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
        </el-col>
      </el-row>
    </div>

    <div v-show="multiShow && options.multiActions" class="filter-container">
      <el-select v-model="multiNow" :placeholder="selectedLabel" class="filter-item" style="width: 130px" @change="handleOption">
        <el-option
          v-for="item in options.multiActions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>

    <el-table
      v-loading="listLoading"
      :data="dataList.records"
      :header-cell-style="{'background':'#f2f3f4', 'color':'#555', 'font-weight':'bold', 'line-height':'32px'}"
      border
      fit
      highlight-current-row
      @selection-change="handleSelection"
    >
      <el-table-column
        v-if="options.multi"
        align="center"
        type="selection"
        width="55"
      />
      <slot name="data-columns" />
    </el-table>

    <pagination v-show="dataList.total>0" :total="dataList.total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="onPagination" />
  </div>
</template>

<script>
import _ from 'lodash'
import {changeState, deleteData, fetchList} from '@/api/common'
import Pagination from '@/components/Pagination'

export default {
  name: 'PagingTable',
  components: { Pagination },
  props: {
    options: {
      type: Object,
      default: () => ({
        multiActions: [],
        listUrl: '/exam/api',
        deleteUrl: '',
        stateUrl: '',
        multi: false
      })
    },
    listQuery: {
      type: Object,
      required: true // 父组件必须传入参数对象
    }
  },
  data() {
    return {
      dataList: { total: 0, records: [] },
      listLoading: false,
      selectedIds: [],
      selectedObjs: [],
      selectedLabel: '',
      multiShow: false,
      multiNow: ''
    }
  },
  created() {
    this.debouncedGetList = _.debounce(this._getList, 300)
    this.getList() // 初始化调用
  },
  watch: {
    listQuery: {
      handler() {
        this.getList() // 查询参数变了触发防抖请求
      },
      deep: true
    }
  },
  methods: {
    getList() {
      this.debouncedGetList()
    },
    _getList() {
      this.listLoading = true
      const params = { ...this.listQuery, t: Date.now() }
      fetchList(this.options.listUrl, params).then(response => {
        this.dataList = {
          ...response.data,
          total: parseInt(response.data.total),
        }
        this.listLoading = false
        this.$emit('list-loaded', this.dataList)
      }).catch(() => {
        this.listLoading = false
      })
    },
    onPagination(page) {
      // 外部 pagination 触发时同步更新 current，调用getList
      this.$emit('update:listQuery', { ...this.listQuery, current: page })
    },
    handleAdd() {
      if (this.options.addRoute) {
        this.$router.push({ name: this.options.addRoute, params: {} })
      } else {
        console.warn('未设置添加路由')
      }
    },
    handleSelection(val) {
      this.selectedIds = val.map(row => row.id)
      this.selectedObjs = val
      this.multiShow = this.selectedIds.length > 0
      this.selectedLabel = `已选${this.selectedIds.length}项`
      this.$emit('select-changed', { ids: this.selectedIds, objs: this.selectedObjs })
    },
    handleOption(v) {
      this.multiNow = ''
      if (v === 'delete') return this.handleDelete()
      if (v === 'enable') return this.handleState(0)
      if (v === 'disable') return this.handleState(1)
      this.$emit('multi-actions', { opt: v, ids: this.selectedIds })
    },
    handleState(state) {
      changeState(this.options.stateUrl, this.selectedIds, state).then(res => {
        if (res.code === 0) {
          this.$message.success('状态修改成功!')
          this.getList()
        }
      })
    },
    handleDelete() {
      if (!this.selectedIds.length) {
        this.$message.warning('请至少选择一条数据！')
        return
      }
      this.$confirm('确实要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteData(this.options.deleteUrl, this.selectedIds).then(() => {
          this.$message.success('删除成功!')
          this.getList()
        })
      })
    }
  }
}
</script>
